<?php

/**
 * Description of UserModel
 *
 * @author gg
 */
namespace User\Model;
use Think\Model;
/**
 * 新建用户流程：
 * 传入用户名以及密码到UpdatePW，如果返回值不为false则将其插入数据库
 * 
 * 更新密码流程：
 * 先验证密码，传入用户名及密码到UpdatePW，如果返回值不为false则将其更新
 * 
 * 
 */
class UserModel extends Model{
    
    protected $insertFields = array('username','passwd','salt');
    protected $updateFields = array('passwd','salt');
    
    private $saltChar = array("!","#","$","%","&","'","(",")","*",
        "+",",","-",".","0","1","2","3","4","5","6","7","8","9",":",";",
        "<","=",">","?","@","A","B","C","D","E","F","G","H","I",
        "J","K","L","M","N","O","P","Q","R","S","T","U","V","W",
        "X","Y","Z","[","]","^","_","`","a","b","c","d","e","f","g","h",
        "i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x",
        "y","z","{","|","}");
    
    /**
     * 获取salt
     * @return String Salt
     */
    private function GetSalt(){
        $salt = "";
        for ($a=0;$a<8;$a++){
            $salt .= $this->saltChar[rand(0, count($this->saltChar))];
        }
        return $salt;
    }
    /**
     *  用户名查重
     * @param String $username 用户名
     * @return boolean true为没有重名，false为有重名 
     */
    public function CheckUsername($username){
        $condition["username"]=$username;
        $return = $this->where($condition)->find();
        return $return==NULL;
    }
    /**
     * Salt查重
     * @param type $salt 
     * @return boolean true为没有重复，false为有重复 
     */
    public function CheckSalt($salt){
        $condition["salt"]=$salt;
        $return = $this->where($condition)->find();
        return $return==NULL;
    }

    /**
     * 获取Salt并且对密码进行加密
     * @param type $data 用户数据，username以及passwd
     * @return false为信息不全，成功则返回加密后的字符串
     */
    public function UpdatePW($data){
        if ((isset($data["username"]))and(isset($data["passwd"]))){
            do {
                $data["salt"] = $this->GetSalt();
            } while (!$this->CheckSalt($data["salt"]));
            $data["passwd"] = md5(md5($data["passwd"]).md5($data["salt"]));
            return $data;
        }  else {
            return FALSE;
        }
    }
    
    /**
     * 检查用户名密码（用于登录及密码修改的验证）
     * @param type $data 用户数据，username以及passwd
     * @return boolean false为不通过，true为通过
     */
    public function CheckUser($data){
        if ((isset($data["username"]))and(isset($data["passwd"]))){
            $condition["username"]=$data["username"];
            $return = $this->where($condition)->find();
            if (($return==FALSE)or($return==NULL)){
                return FALSE;
            }
            return ($return["passwd"]==md5(md5($data["passwd"]).md5($return["salt"])));
        }  else {
            echo 1;
            return FALSE;
        }
    }
}
